<template>
  <el-input ref="refInput"
            v-bind="$attrs"
            @clear="handleClear"
            @input="handleInput">
    <template v-for="(_value, name) in $slots" #[name]="slotData">
      <slot :name="name" v-bind="slotData || {}" />
    </template>
  </el-input>
</template>

<script setup>
import {ref, onMounted, getCurrentInstance, nextTick, reactive, toRefs} from 'vue'
import DkInputUtil from "./DkInputUtil"

const props = defineProps({
  // 是否开启宽度自适应
  autoWidth: {
    type: Boolean,
    default: false
  }
})

const defaultWidth = ref('1px')
const refInput = ref()

const data = reactive({
  inputElement: null,
  inputElementChildWidth: null
})

const { inputElement, inputElementChildWidth} = toRefs(data)

const initDefaultWidth = () => {
  nextTick(() => {
    if (inputElement.value) {
      const inputStyle = window.getComputedStyle(inputElement.value)
      const innerInput = inputElement.value.querySelector('.el-input__inner')
      inputElementChildWidth.value = innerInput.offsetWidth
      const { width } = inputStyle
      defaultWidth.value = width
    }
  })
}

onMounted(() => {
  if (refInput.value && refInput.value.$el) {
    inputElement.value = refInput.value.$el
    initDefaultWidth()
  }
})

const handleClear = () => {
  if (inputElement.value) inputElement.value.style.width = defaultWidth.value
}

const handleInput = val => {
  if (props) {
    const strWidth = DkInputUtil.getStrWidth(val)
    if (inputElement.value) {
      // gapDom 父dom 和 子dom 宽度不一致，需要计算差数
      const gapDom = parseFloat(defaultWidth.value) - parseFloat(inputElementChildWidth.value)
      // 最终的宽度 = 文字实际宽度 + 差数
      const _w = strWidth + gapDom
      // 如果最终宽度 > 默认最大盒子宽度，那么赋值， 不然出出现抖动情况
      if (_w > parseInt(defaultWidth.value)) {
        inputElement.value.setAttribute('style', `width: ${_w}px !important`)
      }
    }
  }
}

</script>